const { ccclass, property } = cc._decorator;

@ccclass
export default class bgMountain extends cc.Component {
    @property([cc.SpriteFrame])
    bg: cc.SpriteFrame[] = [];
    @property
    MountainSpeed: number = 0;//山脉移动系数

    _bgW: number = 0;
    _worldW: number = 0;

    init() {

        this._bgW = this.bg[0].getRect().width;
        this._worldW = HeroHelper.getInstance().widthScene;

        let _w = (this._worldW - cc.winSize.width) * this.MountainSpeed;//最大移动距离
        let firstW = 0, ii = 0;
        let isodd: boolean = false;
        let count = Math.ceil((_w + cc.winSize.width) / this._bgW);//需要的背景块数
        let p1 = count % 2;
        if (p1 == 1) {
            this.addBgNode(0, 0, true);
            ii++;
            isodd = true;
            firstW = this._bgW;
        }
        else {
            firstW = this._bgW / 2;
        }
        let p2 = Math.floor(count / 2);
        for (let index = 0; index < p2; index++) {
            firstW += index * this._bgW;
            this.addBgNode(ii, firstW, isodd);
            this.addBgNode(ii, 0 - firstW, isodd);
            ii++;
        }
    }
    addBgNode(index: number, xx: number, isodd: boolean) {
        let node = new cc.Node();
        node.anchorY = this.node.anchorY;
        let sprite = node.addComponent(cc.Sprite);
        if (xx >= 0)
            sprite.spriteFrame = this.getSpriteR(index);
        else
            sprite.spriteFrame = this.getSpriteL(index, isodd);
        node.x = xx;
        this.node.addChild(node);
    }
    private getSpriteL(index: number, isodd: boolean): cc.SpriteFrame {
        let _index = index;
        if (index >= this.bg.length) {
            _index = index % this.bg.length;
        }
        if (isodd) {
            if (isodd && _index == 0) {
                return this.bg[0].clone();
            }
            else if (_index == 0) {
                return this.bg[this.bg.length - 1].clone();
            }
            else {
                return this.bg[this.bg.length - _index].clone();
            }
        }
        else {
            return this.bg[this.bg.length - 1 - _index].clone();
        }


    }
    private getSpriteR(index: number): cc.SpriteFrame {
        if (index >= this.bg.length) {
            let _index = index % this.bg.length;
            return this.bg[_index].clone();
        }
        else {
            return this.bg[index];
        }
    }
    update(dt: number) {
        this.node.x = 0 - HeroHelper.getInstance().cameraPosition.x * this.MountainSpeed;
    }
}
